using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using System;
using System.Security.Claims;

namespace DesktopWidgetApp.Server.API.Controllers
{
    /// <summary>
    /// 控制器基类
    /// 提供通用功能供其他控制器继承使用
    /// </summary>
    [Authorize]
    public class BaseController : ControllerBase
    {
        /// <summary>
        /// 获取当前用户ID
        /// </summary>
        /// <returns>当前用户的GUID，如果无法获取则返回null</returns>
        protected Guid? GetCurrentUserId()
        {
            var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
            if (string.IsNullOrEmpty(userIdClaim))
            {
                return null;
            }
            
            if (Guid.TryParse(userIdClaim, out var userId))
            {
                return userId;
            }
            
            return null;
        }
        
        /// <summary>
        /// 获取当前用户ID并验证
        /// 如果无法获取或无效，返回401未授权
        /// </summary>
        /// <returns>当前用户的GUID</returns>
        /// <exception cref="UnauthorizedAccessException">当用户未登录或身份无效时抛出</exception>
        protected Guid GetCurrentUserIdOrThrow()
        {
            var userId = GetCurrentUserId();
            if (!userId.HasValue)
            {
                throw new UnauthorizedAccessException("用户未登录或身份验证失败");
            }
            
            return userId.Value;
        }
    }
}